<script setup>
import { ref, onMounted, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app';
import { getDishDetailAPI, getDishScoreAPI, submitDishScoreAPI } from '@/api/dish'
import { addCollectDishAPI, deleteCollectDishAPI,isCollectDishAPI} from '@/api/collect'
import { recordUserBehaviorAPI } from '@/api/user'
import { useUserStore } from '@/stores'

const userStore = useUserStore()

// 菜品ID
const dishId = ref('')
const dishInfo = ref({}) // 初始化空对象，避免undefined报错
const loading = ref(true)

// 用户评分（默认0，未评分状态）
const userRating = ref(0)
const ratingTexts = ['极差', '失望', '一般', '满意', '惊喜']

// 收藏状态（默认未收藏）
const isCollecting = ref(false)
const collectionLoading = ref(false) // 收藏操作加载状态

// 评分文本计算
const getRatingText = computed(() => {
  if (userRating.value === 0) return ''
  const index = Math.ceil(userRating.value) - 1
  return ratingTexts[index] || ''
})

// 难度颜色计算（处理字段缺失情况）
const getDifficultyColor = computed(() => {
  const difficulty = dishInfo.value.difficulty
  if (!difficulty) return '#909399' // 字段不存在时默认灰色
  if (difficulty === '简单') return '#67C23A'
  if (difficulty === '中等') return '#E6A23C'
  if (difficulty === '困难') return '#F56C6C'
  return '#909399'
})

// 口味颜色映射
const flavorColors = {
  '酸': '#FF9F40',
  '甜': '#FF6B6B',
  '苦': '#4ECDC4',
  '辣': '#FF5252',
  '咸': '#45B7D1',
  '麻': '#9B59B6',
  '香': '#F39C12'
}

// 加载菜品详情
const loadDishDetail = async () => {
  loading.value = true
  try {
    const res = await getDishDetailAPI(dishId.value)
    if (res && res.data) {
      // 统一字段映射
      dishInfo.value = {
        image: res.data.image,
        name: res.data.dishName || '未知菜品',
        reviewCount: res.data.ratingCount || 0,
        price: res.data.price || 0,
        location: res.data.location || '未知位置',
        shop: res.data.merchant || '未知商家',
        merchantId: res.data.merchantId || '',
        heat: res.data.calorie || 0,
        rating : res.data.dishRating || 0,
        ingredients: res.data.ingredients || [],
        description: res.data.description || '暂无菜品介绍',
        flavor: res.data.flavor || [],    //['酸'，'甜'，'苦'，'辣'，'咸']
        nutrition: res.data.nutrition || null,
        tags: res.data.tags || []
      }
    } else {
      uni.showToast({ title: '菜品信息获取失败', icon: 'none' })
    }
  } catch (error) {
    console.error('加载菜品详情失败:', error)
    uni.showToast({ title: '加载失败，请重试', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 加载用户评分
const loadScore = async () => {
  try {
    if (!userStore.userInfo?.id) {
      userRating.value = 0
      return
    }
    const res = await getDishScoreAPI(userStore.userInfo.id, dishId.value)
    userRating.value = res?.data?.score !== null && res?.data?.score !== undefined 
      ? Number(res.data.score) 
      : 0
  } catch (error) {
    console.error('加载用户评分失败:', error)
    userRating.value = 0
  }
}

// 提交评分
const submitRating = async () => {
  if (userRating.value <= 0) {
    return uni.showToast({ title: '请先选择评分', icon: 'none' })
  }
  if (!userStore.userInfo?.id) {
    // 未登录时跳转到登录页
    uni.showToast({ title: '请先登录', icon: 'none' })
    return uni.navigateTo({ url: '/pages/Profile/index' })
  }

  try {
    await submitDishScoreAPI(userStore.userInfo.id, dishId.value, userRating.value)
    uni.showToast({ title: `感谢您的评分！`, icon: 'success' })
    // 提交后刷新菜品详情
    setTimeout(async () => {
      await loadDishDetail()
      await loadScore()
    }, 1000)
  } catch (error) {
    console.error('提交评分失败:', error)
    uni.showToast({ title: '提交失败，请稍后重试', icon: 'none' })
  }
}

// 切换收藏状态
const toggleCollection = async () => {
  if (collectionLoading.value) return
  if (!userStore.userInfo?.id) {
    // 未登录时跳转到登录页
    uni.showToast({ title: '请先登录', icon: 'none' })
    return uni.navigateTo({ url: '/pages/login/index' })
  }

  collectionLoading.value = true
  try {
    let res
    if(isCollecting.value) {
      // 取消收藏
      res = await deleteCollectDishAPI([dishId.value])
    } else {
      // 添加收藏
      res = await addCollectDishAPI(dishId.value)
      recordUserBehaviorAPI(userStore.userInfo.id, dishId.value, 'collect')
    }

    if (res?.code === 1) {
      // 添加收藏状态切换动画
      const temp = isCollecting.value
      isCollecting.value = !temp
      dishInfo.value.isCollected = isCollecting.value
      uni.showToast({ 
        title: isCollecting.value ? '收藏成功' : '取消收藏', 
        icon: 'success' 
      })
    } else {
      uni.showToast({ title: '操作失败', icon: 'none' })
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    uni.showToast({ title: '操作失败，请重试', icon: 'none' })
  } finally {
    collectionLoading.value = false
  }
}

// 跳转到店铺详情
const goToShopDetail = () => {
  if (dishInfo.value.merchantId) {
    uni.navigateTo({ url: `/pages/ShopDetail/index?id=${dishInfo.value.merchantId}` })
  } else {
    uni.showToast({ title: '暂无店铺信息', icon: 'none' })
  }
}

// 页面初始化
onLoad( async (options) => {
  dishId.value = options.dishId || ''

  if (dishId.value) {
    if(userStore.userInfo.id) {
      await recordUserBehaviorAPI(userStore.userInfo.id, dishId.value, 'click')
      const res= await isCollectDishAPI(userStore.userInfo.id, dishId.value)
      if(res.data){
        isCollecting.value = true
      }
    }
    loadDishDetail()
    loadScore()
  } else {
    uni.showToast({ title: '参数错误', icon: 'none' })
    loading.value = false
  }
})
</script>

<template>
  <view class="dish-detail-container">
    <!-- 菜品图片区域 -->
    <view class="dish-images-section">
      <view v-if="loading" class="loading-container">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
      
      <view v-else class="single-image-container">
        <image 
          :src="dishInfo.image || '/static/images/default.png'" 
          class="dish-image" 
          mode="aspectFill" 
        />
        
        <!-- 收藏按钮 -->
        <view class="collect-btn" @click="toggleCollection">
          <text 
            class="iconfont icon-jingxuan" 
            :class="[
              collectionLoading ? 'loading' : ''
            ]"
            :style="{ color: isCollecting ? '#FF6B6B' : '#fff' }"
          ></text>
          <view v-if="collectionLoading" class="collect-loading"></view>
        </view>
      </view>
    </view>

    <!-- 菜品基本信息 -->
    <view class="dish-info-section" v-if="!loading">
      <view class="dish-header">
        <view class="dish-title-row">
          <text class="dish-title">{{ dishInfo.name }}</text>
          <view class="price-info">
            <text class="current-price">￥{{ typeof dishInfo.price === 'number' ? dishInfo.price.toFixed(2) : (dishInfo.price || '--') }}</text>
    <text v-if="dishInfo.originalPrice && dishInfo.originalPrice > dishInfo.price" 
      class="original-price">￥{{ typeof dishInfo.originalPrice === 'number' ? dishInfo.originalPrice.toFixed(2) : dishInfo.originalPrice }}</text>
          </view>
        </view>

        <view class="dish-meta">
          <view class="meta-item" @click="goToShopDetail">
            <text class="iconfont icon-shangpu"></text>
            <text class="meta-text">{{ dishInfo.shop }}</text>
            <text class="iconfont icon-arrow"></text>
          </view>
          
          <view class="meta-item">
            <text class="iconfont icon-weizhi"></text>
            <text class="meta-text">{{ dishInfo.location }}</text>
          </view>
          
          <view class="meta-item">
            <text class="iconfont icon-reliang"></text>
            <text class="meta-text">{{ dishInfo.heat }} 千卡</text>
          </view>
        </view>

        <view class="dish-stats">
          <view class="stat-item">
            <text class="iconfont icon-pingfen"></text>
            <text class="stat-value">{{ typeof dishInfo.rating === 'number' ? dishInfo.rating.toFixed(1) : (dishInfo.rating || '--') }}</text>
            <uni-rate 
              :value="dishInfo.rating" 
              :readonly="true" 
              :size="16"
              color="#ffd700"
            />
            <text class="stat-label">({{ dishInfo.reviewCount }}人评价)</text>
          </view>
          
          <view class="stat-item" v-if="dishInfo.prepTime">
            <text class="iconfont icon-shizhong"></text>
            <text class="stat-value">{{ dishInfo.prepTime }}</text>
            <text class="stat-label">制作时间</text>
          </view>
          
          <view class="stat-item" v-if="dishInfo.difficulty">
            <text class="iconfont icon-nandu"></text>
            <text class="stat-value" :style="{ color: getDifficultyColor }">{{ dishInfo.difficulty }}</text>
            <text class="stat-label">难度</text>
          </view>
        </view>

        <!-- 菜品标签 -->
        <view class="dish-tags" v-if="dishInfo.tags && dishInfo.tags.length">
          <text
            v-for="tag in dishInfo.tags"
            :key="tag"
            class="dish-tag"
          >
            {{ tag }}
          </text>
        </view>
      </view>
    </view>

    <!-- 菜品描述 -->
    <view class="dish-description-section" v-if="!loading">
      <view class="section-header">
        <text class="section-title">
          <text class="iconfont icon-wenben"></text>
          菜品介绍
        </text>
      </view>
      <view class="description-content">
        <text>{{ dishInfo.description }}</text>
      </view>
    </view>

    <!-- 菜品口味展示区域 - 新增内容 -->
    <view class="flavor-section" v-if="!loading && dishInfo.flavor && dishInfo.flavor.length">
      <view class="section-header">
        <text class="section-title">
          <text class="iconfont icon-weidudengji"></text>
          口味特点
        </text>
        <text class="section-subtitle">该菜品主要口味特征</text>
      </view>
      <view class="flavor-content">
        <view 
          v-for="(flavor, index) in dishInfo.flavor" 
          :key="index" 
          class="flavor-item"
          :style="{ backgroundColor: flavorColors[flavor] + '10', borderColor: flavorColors[flavor] + '30' }"
        >
          <view 
            class="flavor-indicator"
            :style="{ backgroundColor: flavorColors[flavor] }"
          ></view>
          <text class="flavor-text" :style="{ color: flavorColors[flavor] }">{{ flavor }}</text>
        </view>
      </view>
    </view>

    <!-- 食材配料 -->
    <view class="ingredients-section" v-if="!loading && dishInfo.ingredients && dishInfo.ingredients.length">
      <view class="section-header">
        <text class="section-title">
          <text class="iconfont icon-shicai"></text>
          主要食材
        </text>
      </view>
      <view class="ingredients-list">
        <view
          v-for="(ingredient, index) in dishInfo.ingredients"
          :key="index"
          class="ingredient-item"
        >
          {{ ingredient.name || '未知食材' }}
        </view>
      </view>
    </view>

    <!-- 用户评分区域 -->
    <view class="rating-section" v-if="!loading">
      <view class="section-header">
        <text class="section-title">
          <text class="iconfont icon-pingfen"></text>
          为这道菜评分
        </text>
        <text class="section-subtitle">您的评分将帮助其他用户了解这道菜</text>
      </view>
      <view class="rating-content">
        <uni-rate 
          v-model="userRating" 
          :size="32"
          active-color="#FFB800"
          void-color="#F0F0F0"
          allow-half
          touchable
        />
        <text class="rating-text" v-if="getRatingText">{{ getRatingText }}</text>
        <button
          type="primary"
          @click="submitRating"
          :disabled="userRating <= 0"
          class="submit-rating-btn"
        >
          提交评分
        </button>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
// 基础容器样式
.dish-detail-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding-bottom: calc(80rpx + env(safe-area-inset-bottom));

  // 所有内容区块通用样式
  .dish-info-section,
  .dish-description-section,
  .ingredients-section,
  .rating-section,
  .flavor-section {  // 添加新的区块
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    margin: 32rpx;
    border-radius: 32rpx;
    padding: 40rpx;
    box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.08);
    border: 2rpx solid rgba(255, 255, 255, 0.2);
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 4rpx;
      background: linear-gradient(90deg, #667eea, #764ba2, #f093fb, #f5576c);
      background-size: 200% 100%;
      animation: gradientShift 3s ease-in-out infinite;
    }
  }

  // 区域标题样式
  .section-header {
    margin-bottom: 32rpx;

    .section-title {
      display: flex;
      align-items: center;
      gap: 16rpx;
      margin: 0 0 8rpx 0;
      font-size: 32rpx;
      color: #333;
      font-weight: 600;

      .iconfont {
        font-size: 36rpx;
        color: #667eea;
      }
    }

    .section-subtitle {
      font-size: 24rpx;
      color: #999;
      display: block;
    }
  }
}

// 加载状态样式
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 40rpx;
  color: #666;

  .loading-spinner {
    width: 64rpx;
    height: 64rpx;
    border: 6rpx solid rgba(102, 126, 234, 0.2);
    border-top: 6rpx solid #667eea;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 32rpx;
  }

  text {
    font-size: 28rpx;
    opacity: 0.8;
  }
}

// 菜品图片区域
.dish-images-section {
  position: relative;
  height: 500rpx;
  overflow: hidden;

  .single-image-container {
    position: relative;
    width: 100%;
    height: 100%;

    .dish-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}

// 收藏按钮
.collect-btn {
  position: absolute;
  top: 40rpx;
  right: 40rpx;
  width: 88rpx;
  height: 88rpx;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
  z-index: 10;
  cursor: pointer;
  transition: all 0.3s ease;

  .iconfont {
    font-size: 60rpx;
    transition: all 0.3s ease;
    position: relative;
    z-index: 2;
  }

  // 收藏中加载动画
  .collect-loading {
    position: absolute;
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid rgba(255, 255, 255, 0.3);
    border-top: 4rpx solid #fff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  &:active {
    transform: scale(0.9);
  }

  .icon-shoucang-fill {
    animation: bounce 0.5s ease;
  }
}

// 菜品基本信息
.dish-info-section {
  margin-top: -100rpx;
  z-index: 5;
  position: relative;

  .dish-header {
    .dish-title-row {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      margin-bottom: 32rpx;

      .dish-title {
        font-size: 44rpx;
        font-weight: 700;
        color: #333;
        flex: 1;
        margin-right: 24rpx;
        background: linear-gradient(45deg, #667eea, #764ba2);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }

      .price-info {
        display: flex;
        flex-direction: column;
        align-items: flex-end;

        .current-price {
          font-size: 36rpx;
          font-weight: 700;
          color: #e85d5d;
        }

        .original-price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
          margin-top: 4rpx;
        }
      }
    }

    .dish-meta {
      display: flex;
      flex-direction: column;
      gap: 16rpx;
      margin-bottom: 32rpx;

      .meta-item {
        display: flex;
        align-items: center;
        gap: 16rpx;
        padding: 16rpx 24rpx;
        background: rgba(102, 126, 234, 0.05);
        border-radius: 24rpx;
        border: 2rpx solid rgba(102, 126, 234, 0.1);

        .iconfont {
          font-size: 28rpx;
          color: #667eea;
          flex-shrink: 0;
        }

        .meta-text {
          font-size: 28rpx;
          color: #333;
          flex: 1;
        }

        &:first-child {
          cursor: pointer;
          transition: all 0.3s ease;

          &:active {
            background: rgba(102, 126, 234, 0.1);
            transform: scale(0.98);
          }
        }
      }
    }

    .dish-stats {
      display: flex;
      justify-content: space-around;
      gap: 24rpx;
      margin-bottom: 32rpx;
      padding: 24rpx;
      background: rgba(102, 126, 234, 0.05);
      border-radius: 24rpx;

      .stat-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8rpx;
        flex: 1;

        .iconfont {
          font-size: 32rpx;
          color: #667eea;
        }

        .stat-value {
          font-size: 28rpx;
          font-weight: 600;
          color: #333;
        }

        .stat-label {
          font-size: 24rpx;
          color: #666;
        }
      }
    }

    .dish-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx;

      .dish-tag {
        background: rgba(102, 126, 234, 0.1);
        color: #667eea;
        border: 2rpx solid rgba(102, 126, 234, 0.2);
        padding: 8rpx 24rpx;
        border-radius: 24rpx;
        font-size: 24rpx;
        font-weight: 500;
      }
    }
  }
}

// 菜品描述
.dish-description-section {
  .description-content {
    text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.8;
      display: block;
    }
  }
}

// 菜品口味展示样式 - 新增内容
.flavor-section {
  .flavor-content {
    display: flex;
    flex-wrap: wrap;
    gap: 24rpx;
    padding: 16rpx;
    justify-content: center;
  }
  
  .flavor-item {
    display: flex;
    align-items: center;
    gap: 16rpx;
    padding: 16rpx 32rpx;
    border-radius: 32rpx;
    border: 2rpx solid;
    transition: all 0.3s ease;
    cursor: default;
    
    &:active {
      transform: translateY(4rpx);
    }
  }
  
  .flavor-indicator {
    width: 20rpx;
    height: 20rpx;
    border-radius: 50%;
  }
  
  .flavor-text {
    font-size: 28rpx;
    font-weight: 600;
  }
}

// 食材配料
.ingredients-section {
  .ingredients-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;

    .ingredient-item {
      display: flex;
      align-items: center;
      gap: 12rpx;
      padding: 12rpx 24rpx;
      background: rgba(103, 194, 58, 0.1);
      color: #67c23a;
      border-radius: 20rpx;
      font-size: 26rpx;
      border: 2rpx solid rgba(103, 194, 58, 0.2);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;

      .iconfont {
        font-size: 20rpx;
      }
    }
  }
}

// 用户评分区域
.rating-section {
  text-align: center;

  .rating-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 32rpx;

    .rating-text {
      font-size: 32rpx;
      color: #667eea;
      font-weight: 600;
    }

    .submit-rating-btn {
      background: linear-gradient(45deg, #667eea, #764ba2);
      border: none;
      padding: 20rpx 48rpx;
      font-weight: 600;
      border-radius: 40rpx;
      color: white;
      font-size: 28rpx;
      width: 240rpx;
      cursor: pointer;
      transition: all 0.3s ease;
      margin-top: 16rpx;
      opacity: 1;
      transform: scale(1);

      &:active {
        transform: scale(0.95);
      }

      &[disabled] {
        background: #ddd !important;
        color: #999 !important;
        cursor: not-allowed;
        opacity: 0.7;
      }
    }
  }
}

// 动画定义
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes gradientShift {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

@keyframes bounce {
  0% { transform: scale(1); }
  50% { transform: scale(1.3); }
  100% { transform: scale(1); }
}

// 小程序样式适配
/* #ifdef MP-WEIXIN */
.dish-info-section,
.dish-description-section,
.ingredients-section,
.rating-section,
.flavor-section {  // 添加新的区块
  background: rgba(255, 255, 255, 0.98) !important;
  backdrop-filter: none !important;
  box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.06) !important;
}

.dish-title {
  color: #667eea !important;
  background: none !important;
  background-clip: unset !important;
  -webkit-background-clip: unset !important;
  -webkit-text-fill-color: unset !important;
}

// 小程序按钮适配
.submit-rating-btn {
  line-height: normal !important;
}
/* #endif */

// 响应式 - 小屏幕适配
@media (max-width: 768rpx) {
  .dish-detail-container {
    .dish-info-section,
    .dish-description-section,
    .ingredients-section,
    .rating-section,
    .flavor-section {
      margin: 24rpx;
      padding: 32rpx;
    }

    .dish-images-section {
      height: 400rpx;
    }

    .dish-stats {
      flex-direction: column !important;
      gap: 16rpx !important;

      .stat-item {
        flex-direction: row !important;
        justify-content: space-between !important;
      }
    }
  }
}

// 平板适配
@media (min-width: 768px) {
  .dish-detail-container {
    max-width: 800rpx;
    margin: 0 auto;
  }

  .dish-images-section {
    height: 600rpx;
  }
}
</style>